<?php

namespace Queue\ProcessInvoker;

use Queue\Interfaces\{
    ProcessInvokerInterface,
    TaskInterface,
};

final class WindowsProcessInvoker implements ProcessInvokerInterface
{
    public function run(TaskInterface $task, string $worker): int
    {
        $pid = 0;
        $cmd = \sprintf(
            "php %s %s",
            $worker,
            \base64_encode(\serialize($task))
        );
        $cmd = 'wmic process call create "'.$cmd.'" | find "ProcessId"';
        $handle = \popen("start /B ". $cmd, "r");
        $read = \fread($handle, 200); //Read the output 
        $pid = \substr($read, \strpos($read, '=') + 1);
        $pid = \substr($pid, 0, \strpos($pid, ';') );
        $pid = (int) $pid;
        \pclose($handle);

        return $pid;
    }

    public function isRunning(int $pid): bool
    {
        $result = \shell_exec('tasklist /FI "PID eq '.$pid.'"' );

        return \count(\preg_split("/\n/", $result)) > 0
            && !\preg_match('/No tasks/', $result)
            ;
    }
}
